﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.Utilities;
using NLog;
using Microsoft.Extensions.Logging;
using System.Text.Encodings.Web;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using chihuopig.Service;
using chihuopig.Tool;
using chihuopig.IService;
using System.Text;
namespace chihuopig.Web.Framework
{
    public class MemberController :WebViewController  
    {
        private readonly ILogger<MemberController> _logger;
        chihuopig.Model.Member _Member;
        ImemberService _imemberService;
        public MemberController(ILogger<MemberController> logger, ImemberService imemberService)
        {
            _logger = logger;
            _imemberService = imemberService;
        }

        protected chihuopig.Model.Member member
        {
            get
            {
                if (_Member==null)
                {
                    string id = UtilityHelper.MemberGetCookieValue(CookieKeysCollection.Buffalo_User_Key);

                    if (string.IsNullOrEmpty(id))
                    {
                        return null;
                    }
                    return chihuopig.Service.DBService.Sqlclient.Queryable<chihuopig.Model.Member>().Where(s => s.Id.ToString() == id).Single();
                }

                return _Member;
            }
            private set
            {
                _Member = value;

            }
        }


        public override void OnActionExecuting(ActionExecutingContext context)
        {
            
            //logger.Debug<string>("微信登录来了");
            var state = "JeffreySu-" + DateTime.Now.Millisecond;
            var Getmember = member;
            string url = $"http://{HttpContext.Request.Host}{ Request.Path}";
           
            if(PlatformType.WeixinApp== GetPlatformType)
            {
                string RequestOpenId = Request.Query["OpenId"];
                var findMember = _imemberService.FindOpenId(RequestOpenId);
                if (!string.IsNullOrEmpty(RequestOpenId)&& findMember==null)
                {
                    context.Result=new ContentResult() { Content = "{\"success\":\"ture\"}", ContentType = "application/json" };
                    return;
                }

                context.Result = new ContentResult() { Content = "{\"success\":\"false\"}", ContentType = "application/json" };
            }
            else if (PlatformType.Weixin == GetPlatformType)
            {

                //_logger.LogDebug("微信登录来了");
                string code = Request.Query["code"];
               // _logger.LogDebug($"微信登录来了 code={code} ");
                if (member==null)//如果为membernull就去授权
                { 
                    if (string.IsNullOrWhiteSpace(code))
                    {
                         string OAuthUrl = OAuthApi.GetAuthorizeUrl("wxd4e326f09ae7cbc5", url, state, Senparc.Weixin.MP.OAuthScope.snsapi_userinfo);

                         context.Result = new RedirectResult(OAuthUrl);
                       
                    }
                    else
                    {

                       // _logger.LogDebug($"用户已经同意了 code={code} ");
                        //用户已经同意了
                        OAuthAccessTokenResult token= OAuthApi.GetAccessToken("wxd4e326f09ae7cbc5", "86425e83d61e93f74fffa982e810d3c1", code);
                       // _logger.LogDebug($"用户已经同意了 OAuthAccessTokenResult ");
                        OAuthUserInfo UserInfo=OAuthApi.GetUserInfo(token.access_token, token.openid);
                       // _logger.LogDebug($"OAuthApi.GetUserInfo(token.access_token, token.openid) ");
                        var findMember = _imemberService.FindOpenId(UserInfo.openid);
                        if (findMember==null)
                        {
                            _logger.LogDebug($"findMember == null ");
                            long id = _imemberService.Add(new Model.Member() {
                                 Addtime=DateTime.Now,
                                 city= UserInfo.city,
                                 headimgurl=UserInfo.headimgurl,
                                 money=0.00m,
                                 nickname=UserInfo.nickname,
                                 openId=UserInfo.openid,
                                 Sex=UserInfo.sex,
                                 unionid=UserInfo.unionid
                              
                            });
                           
                            //string value = UtilityHelper.DESEncrypt(id.ToString(), CookieKeysCollection.Buffalo_User_Key, CookieKeysCollection.Buffalo_User_IV);
                            UtilityHelper.SetCookie(CookieKeysCollection.Buffalo_User_Key, id.ToString(), DateTime.Now.AddDays(7));
                            member = findMember;
                        }
                        else
                        {
                            //string value = UtilityHelper.DESEncrypt(CookieKeysCollection.Buffalo_User_Key, member.Id.ToString(), CookieKeysCollection.Buffalo_User_IV);
                            UtilityHelper.SetCookie(CookieKeysCollection.Buffalo_User_Key, findMember.Id.ToString(), DateTime.Now.AddDays(7));
                            member = findMember;

                        }


                        //UserInfo.headimgurl
                    }
                }

                //context.Result=new 
            }
            else
            {
                StringBuilder content = new StringBuilder();
                content.Append("<!DOCTYPE html><html><head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=0\">");
                content.Append("</head><body>");
                content.Append("<title>抱歉，出错了</title><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=0\">");
                content.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css\">");
                content.Append("<div class=\"weui_msg\"><div class=\"weui_icon_area\"><i class=\"weui_icon_info weui_icon_msg\"></i></div><div class=\"weui_text_area\"><h4 class=\"weui_msg_title\">请在微信客户端打开链接</h4></div></div>");
                content.Append("</body></html>");
                context.Result = new ContentResult()
                {
                    Content = content.ToString(),
                    ContentType = "text/html; charset=gbk"
                };
                return;
            }


        }

      
    }
}